<template>
  <div>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更新头像</span>
    </div>
    <el-form>
      <el-form-item>
        <el-upload
      :on-change="onSelectFile"
      class="avatar-uploader"
      :show-file-list="false"
      :auto-upload="false"
      style="width: 400px; height: 280px; border: 1px solid #ccc; border-radius: 4px; overflow: hidden; position: relative; ">
      <img v-if="imgUrl" :src="imgUrl" class="avatar" style="width: 100%; height: 100%; object-fit: cover;">
      <i v-else class="el-icon-plus avatar-uploader-icon" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"></i>
    </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary">
      <i class="el-icon-plus"></i>
      选择图片
    </el-button>
    <el-button type="success" :disabled="isSelect" @click="onSubmit">
      <i class="el-icon-upload"></i>
      上传头像
    </el-button>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary">
      <i class="el-icon-plus"></i>
      选择图片
    </el-button>
    <el-button type="success" :disabled="isSelect">
      <i class="el-icon-upload"></i>
      上传头像
    </el-button>
      </el-form-item> -->
    </el-form>
  </el-card>
</div>
</template>

<script>
import { mapActions } from 'vuex'
import { updateAvatarAPI } from '@/api/user'
export default {
  name: 'user-avatar',
  data () {
    return {
      imgUrl: '',
      avatar: '',
      isSelect: true
    }
  },

  methods: {
    ...mapActions('user', ['getUser']),
    onSelectFile (uploadFile) {
      this.imgUrl = URL.createObjectURL(uploadFile.raw) // 预览图片
      if (uploadFile.raw) {
        this.isSelect = false
        const reader = new FileReader()
        reader.readAsDataURL(uploadFile.raw)
        reader.onload = (e) => {
          this.avatar = e.target.result
        }
      }
    },
    // 上传图片到服务器
    async onSubmit () {
      await updateAvatarAPI(this.avatar)
      this.$store.commit('user/setAvatar', this.avatar)
      this.$message.success('上传头像成功')
      this.getUser()
    }

  }
}
</script>

<style>

</style>
